package com.yuki.consumer.interceptor;

import com.alibaba.dubbo.config.annotation.Reference;
import com.yuki.api.annotation.UserLoginToken;
import com.yuki.api.model.UmsAdmin;
import com.yuki.api.service.ITokenService;
import com.yuki.api.service.IUserService;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.jws.soap.SOAPBinding;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author weikun
 * @date 2020/12/31 20:08
 */
@Component //是个注入的组件
public class TokenInterceptor implements HandlerInterceptor {

    @Reference(
            version = "1.0.0", interfaceClass = IUserService.class,
            interfaceName = "com.yuki.api.user.service.IUserService",
            timeout = 120000
    )
    private IUserService service;


    @Reference(
            version = "1.0.0", interfaceClass = ITokenService.class,
            interfaceName = "com.yuki.api.service.ITokenService",
            timeout = 120000
    )
    private ITokenService tokenService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //取出token
        String token = request.getHeader("Authorization");

        //有好多请求方法，该方法是否需要经过HandlerInterceptor 拦截器，如果不是，直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        //是需要拦截的
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();//取出该方法
        //如果该方法需要进行token验证
        if (method.isAnnotationPresent(UserLoginToken.class)) {
            UserLoginToken userLoginToken = method.getAnnotation(UserLoginToken.class);
            if (userLoginToken.required()) {
                //执行验证
                if (token == null) {
                    throw new RuntimeException("无token，请重新登录！");
                }
                //有token1了
                token = token.split("@")[1];
                String userid = tokenService.getUserId(token);
                UmsAdmin umsAdmin = service.findUserById(Long.parseLong(userid));
                if (umsAdmin == null) {
                    throw new RuntimeException("用户不存在，请重新登录！");
                }

                if (tokenService.checkSign(token, umsAdmin.getPassword())) {
                    return true;
                } else {
                    throw new RuntimeException("token验证失败，请重新登录！");
                }
            }
        }
        return true;
    }
}
